import * as api from '@/services/api';
import { Direction } from '@/services/searchParam';

export default {
  namespace: 'global',
  state: {
    flag: 'userCentral',
    isLogin: false,
    start: '菏泽',
    end: '临沂',
    startPoint: '菏泽',
    endPoint: '临沂',
    appId: 'wx787faed660ab15a3',
    direction: 'STARTOEND',
    searchParams: {
      page: 1,
      routeId: '',
      direction: 'STARTOEND',
      entity: '',
      departureTime: '',
      openId: '',
    },
  },
  subscriptions: {
    // @ts-ignore 订阅路由变化
    routeFlag({ history, dispatch }) {
      history.listen((pathname: any) => {
        dispatch({
          type: 'setFlag',
          pathname: pathname,
        });
      });
    },
  },
  effects: {
    // @ts-ignore
    *getRoute(params: any, { call, put }) {
      const data = yield call(api.getRouteInfo, params);
      yield put({
        type: 'saveRoute',
        action: data.data,
      });
    },
  },
  reducers: {
    saveRoute(state: any, action: any) {
      const { startPoint, endPoint, id } = action.action;
      const searchParams = { routeId: id, direction: Direction.STARTOEND };
      localStorage.setItem('startPoint', startPoint);
      localStorage.setItem('endPoint', endPoint);
      localStorage.setItem('start', startPoint);
      localStorage.setItem('end', endPoint);

      return {
        ...state,
        startPoint: startPoint,
        endPoint: endPoint,
        start: startPoint,
        end: endPoint,
        searchParams: searchParams,
      };
    },

    changLocation(state: any, action: any) {
      const {startPoint, endPoint} = localStorage;
      const temp: string = startPoint;
      localStorage.setItem('startPoint', endPoint);
      state.startPoint = endPoint;
      state.endPoint = temp;
      localStorage.setItem('endPoint', temp);

      state.searchParams.direction =
        state.searchParams.direction === Direction.STARTOEND
          ? Direction.ENDTOSTART
          : Direction.STARTOEND;
      return { ...state };
    },

    setFlag(state: any, params: any) {
      const pathName = params.pathname.pathname;
      if (pathName === '/home') {
        state.flag = 'userCentral';
      } else if (pathName === '/user_central') {
        state.flag = 'home';
      } else {
        state.flag = 'home';
      }

      return { ...state };
    },
  },
};
